﻿using System;
using System.Linq;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Collections.Generic;

namespace Ledict.Utility.Extension
{
    /// <summary>
    /// 创建日期：2011-10-27
    /// 作者：陈重
    /// 图片操作类,提供若干静态、扩展方法 
    /// </summary>
    public static class ImageExtensions
    {
        private static readonly string ImageDomain = "192.168.2.137:81";//图片服务器地址
        private static readonly string AvatarBlank = "";//未找到图片默认图片
        /// <summary>
        /// 转成字节流
        /// </summary>
        /// <param name="img">The img.</param>
        /// <param name="format">The format.</param>
        /// <returns></returns>
        public static MemoryStream ToStream(this Image img, ImageFormat format = null)
        {
            var stream = new MemoryStream();
            img.Save(stream, ImageFormat.Jpeg);
            return stream;
        }

        /// <summary>
        /// 转成byte数组
        /// </summary>
        /// <param name="img">The img.</param>
        /// <param name="format">The format.</param>
        /// <returns></returns>
        public static byte[] ToBytes(this Image img, ImageFormat format = null)
        {
            return img.ToStream(format).ToArray();
        }

        /// <summary>
        /// 通过Stream读取，不会锁文件
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public static Image Load(string path)
        {
            var ms = new MemoryStream(File.ReadAllBytes(path));
            var img = Image.FromStream(ms);
            return img;
        }

        /// <summary>
        /// 获取头像某尺寸的地址，如果没有头像则使用默认头像
        /// </summary>
        /// <param name="avatar">库中的路径</param>
        /// <param name="size">头像大小,如:'50x50'</param>
        /// <param name="userOnDelete">在删除时使用，不转换为访问地址</param>
        /// <returns></returns>
        public static string GetSizedAvatarPath(this string avatar, string size,bool userOnDelete=false)
        {
            if (!size.StartsWith("_"))
            {
                size = "_" + size;
            }
            var result=avatar.Insert(avatar.LastIndexOf('.'), size);
            return userOnDelete ? result : result.ToWebDomain();
        }
        /// <summary>
        /// 获取头像某尺寸的地址，如果没有头像则使用默认头像
        /// </summary>
        /// <param name="avatar">库中的路径</param>
        /// <param name="width">要显示的头像宽</param>
        /// <param name="height">要显示的头像高</param>
        /// <returns></returns>
        public static string GetSizedAvatarPath(this string avatar, int width, int height, bool userOnDelete = false)
        {
            return avatar.GetSizedAvatarPath(width.ToString() + "x" + height.ToString(),userOnDelete);
        }

        /// <summary>
        /// 内网图片地址转换成外网域名访问地址
        /// </summary>
        /// <param name="src">The SRC.</param>
        /// <returns></returns>
        public static string ToWebDomain(this string src)
        {
            if (string.IsNullOrEmpty(src))
                return AvatarBlank;
            if (src.StartsWith(@"files://"))
            {
                //var pa = @"^http://((localhost(:\d+?)*)|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)*))/";
                var pa = @"^files://(.+?)/";
                return Regex.Replace(src, pa, @"http://" + ImageDomain + "/");
                //return Regex.Replace(src, pa, x =>
                //{
                //    return x.Groups[0].Value.Replace(x.Groups[1].Value, THZConfig.Instance.SiteSettingsModule.ImageDomain);
                //});
                var begin = src.IndexOf("//") + 2;
                var end = src.IndexOf("/", src.IndexOf("//") + 2);
                return src.Replace(src.Substring(begin, end - begin), ImageDomain);
            }
            else if(src.StartsWith("http"))
            {
                return src;
            }
            else
            {
                return "http://" + ImageDomain + (src.StartsWith("/") ? "" : "/") + src;
            }
        }

        /// <summary>
        /// 描述：获得生成图片的宽度 和 高度（还可以扩展）
        /// 作者：员战强
        /// 日期：2012-03-23
        /// </summary>
        /// <param name="thumbWidth">给定的缩略图的宽度</param>
        /// <param name="thumbHeight">给定的缩略图的高度</param>
        /// <param name="imgWidth">原始图片的宽度</param>
        /// <param name="imgHeight">原始图片的高度</param>
        /// <param name="thumbsMode">获取缩略图的模式</param>
        /// <param name="resultWidth">返回的图片的宽度</param>
        /// <param name="resultHeight">返回的图片的高度</param>
        public static void GetResultWidthAndHeight(int thumbWidth, int thumbHeight, int imgWidth, int imgHeight, ThumbsMode thumbsMode, out int resultWidth, out int resultHeight)
        {
            resultWidth = thumbWidth < imgWidth ? thumbWidth : imgWidth;
            resultHeight = thumbHeight < imgHeight ? thumbHeight : imgHeight;
            if (thumbWidth > imgWidth || thumbHeight > imgHeight)
            {
                switch (thumbsMode)
                {
                    case ThumbsMode.ByWidth:
                        if (imgWidth > thumbWidth)
                        {
                            resultWidth = thumbWidth;
                            resultHeight = imgHeight * thumbWidth / imgWidth;
                        }
                        else
                        {
                            resultWidth = imgWidth;
                            resultHeight = imgHeight;
                        }
                        break;
                    case ThumbsMode.ByHeight:
                        if (imgHeight > thumbHeight)
                        {
                            resultHeight = thumbHeight;
                            resultWidth = imgWidth * thumbHeight / imgHeight;
                        }
                        else
                        {
                            resultWidth = imgWidth;
                            resultHeight = imgHeight;
                        }
                        break;
                }
            }
            else
            {
                if (imgWidth >= imgHeight)
                {
                    resultWidth = thumbWidth;
                    resultHeight = imgHeight * thumbWidth / imgWidth;
                }
                else
                {
                    resultHeight = thumbHeight;
                    resultWidth = imgWidth * thumbHeight / imgHeight;
                }
            }
        }
    }
    public enum ThumbsMode
    {
        /// <summary>
        /// 以宽度为界
        /// </summary>
        ByWidth,
        /// <summary>
        /// 以高度度为界
        /// </summary>
        ByHeight
    }
}
